/*
 * @Descripttion:
 * @LastEditors: chen.long
 * @LastEditTime: 2024-02-24 13:27:19
 */
import { compose, getAbsolutePath } from '../utils';
import { ScriptObjectLoader } from '../types/index.type';
import { StyleObject } from '../types/template.type';
import { loaderOption, plugin, presetLoadersType } from '../types/plugin.type';

/**
 * @Author: chen.long
 * @Descripttion: 获取柯里化之后的 cssLoader
 * @Param:
 * @param {loaderOption} plugins 所有插件集合
 */
export function getCssLoader({ plugins }: loaderOption) {
  return (code: string, src: string = '', base: string): string =>
    compose(plugins.map(plugin => plugin.cssLoader))(code, src, base);
}

/**
 * 转换子应用css内的相对地址成绝对地址
 */
function cssRelativePathResolve(code: string, src: string, base: string) {
  const baseUrl = src ? getAbsolutePath(src, base) : base;
  const urlReg = /(url\((?!['"]?(?:data):)['"]?)([^'")]*)(['"]?\))/g;
  return code.replace(urlReg, (_m, pre, url, post) => {
    const absoluteUrl = getAbsolutePath(url, baseUrl);
    return pre + absoluteUrl + post;
  });
}

/**
 * @Author: chen.long
 * @Descripttion: 获取预置插件
 */
export function getPresetLoaders(
  loaderType: presetLoadersType,
  plugins: Array<plugin>
): plugin[presetLoadersType] {
  const loaders: (StyleObject | ScriptObjectLoader)[][] = plugins
    .map(plugin => plugin[loaderType])
    .filter(loaders => loaders?.length);
  const res = loaders.reduce(
    (preLoaders, curLoaders) => preLoaders.concat(curLoaders),
    []
  );
  return loaderType === 'cssBeforeLoaders' ? res.reverse() : res;
}

const defaultPlugin = {
  cssLoader: cssRelativePathResolve,
  cssBeforeLoaders: [{ content: 'html {view-transition-name: none;}' }]
};

/**
 * @Author: chen.long
 * @Descripttion: 获取所有的插件
 * @Param:
 */
export function getPlugins(): Array<plugin> {
  return [defaultPlugin];
}
